<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link href="assets/css/map.css" rel="stylesheet">
		<link href="assets/css/leaflet.css" rel="stylesheet">
		<title>leaflet</title>
	</head>

	<body>

		<div id="map"></div>
		<div class="btns" style="text-align: center;margin-top: 20px;">
			<button onclick="onClear(1)">清除单个图层</button>
			<button onclick="onClear(2)">清除图层组</button>
			<br>
			<button onclick="onClear(3)">清除图层通用方法，包含所有图层和单个图层**</button>
		</div>

		<script src="assets/js/leaflet.js"></script>
		<script>
			let map = L.map("map", {
				zoom: 12,
				maxZoom: 18,
				center: [34.269701076858354, 108.94729614257814],
			});
			L.tileLayer(
				"http://{s}.tile.osm.org/{z}/{x}/{y}.png"
			).addTo(map);
			const path1 = [{
				"lat": 34.31621838080741,
				"lng": 108.84228283825684
			}, {
				"lat": 34.31650194389378,
				"lng": 108.87522902978287
			}, {
				"lat": 34.296650214700406,
				"lng": 108.87351308230755
			}, {
				"lat": 34.29211201768751,
				"lng": 108.84125326977166
			}, {
				"lat": 34.31593481676314,
				"lng": 108.8419396487618
			}]
			const path2 = [{
				"lat": 34.30175539329721,
				"lng": 108.8999386734274
			}, {
				"lat": 34.29126107845571,
				"lng": 108.94558287627075
			}, {
				"lat": 34.26289150646404,
				"lng": 108.8944476415064
			}]
			const path3 = [{
				"lat": 34.28870820905123,
				"lng": 108.9977476795203
			}, {
				"lat": 34.30827822549175,
				"lng": 109.03652809246239
			}, {
				"lat": 34.26771500911705,
				"lng": 109.01250482780799
			}, {
				"lat": 34.255230080733675,
				"lng": 109.01319120679814
			}, {
				"lat": 34.2557976176794,
				"lng": 109.05162843024517
			}]
			const polygon1 = L.polygon(path1, {
				layerId: 'layerId1',
				weight: 2,
				color: "rgb(53, 146, 241)",
				fillColor: 'rgb(53, 146, 241)',
				opacity: 0.8,
				fillOpacity: 0.4,
			});
			polygon1.addTo(map)

			// 图层组，使用L.FeatureGroup或者L.layerGroup都是可以的
			const layerGroup = new L.FeatureGroup().addTo(map);
			let arr = [path2, path3]
			arr.forEach(item => {
				const polygon = L.polygon(item, {
					weight: 2,
					color: "red",
					fillColor: 'red',
					opacity: 0.8,
					fillOpacity: 0.4,
				});
				layerGroup.addLayer(polygon);
			})

			// 清除图层
			function onClear(type) {
				if (type === 1) {
					// 清除单个图层
					map.removeLayer(polygon1);
				} else if (type === 2) {
					// 清除图层组
					layerGroup.clearLayers();
				} else if (type === 3) {
					// 通用方法
					map.eachLayer((layer) => {
						// 清除所有图层
						map.removeLayer(layer);
						//清除单个图层，layerId自己定义
						// if (layer.options.layerId) {
						// 	map.removeLayer(layer);
						// }
					})
				}
			}
		</script>
	</body>


</html>